package com.gz.controller;

import com.alibaba.fastjson.JSONObject;
import com.gz.dto.*;
import com.gz.entity.*;
import com.gz.service.*;
import com.gz.vo.R;
import com.gz.vo.StuLabelQuestionRes;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * (TestPaper)表控制层
 *
 * @author makejava
 * @since 2024-02-23 17:02:03
 */
@RestController
@RequestMapping("testPaper")
@Api(value = "试卷控制层", tags = {"试卷控制层"})
@Slf4j
public class TestPaperController {

    /**
     * 服务对象
     */
    @Autowired
    private TestPaperService testPaperService;
    /**
     * 服务对象
     */
    @Autowired
    private PaperUserService paperUserService;
    /**
     * 服务对象
     */
    @Autowired
    private PaperQuestionService paperQuestionService;
    /**
     * 服务对象
     */
    @Autowired
    private SuserService suserService;
    /**
     * 服务对象
     */
    @Autowired
    private QuestionService questionService;
    @Autowired
    private StudentQuestionTagWeightsService studentQuestionTagWeightsService;


    @Value("${app.aiPaperQuestionCnt}")
    private String aiPaperQuestionCnt;

    /**
     * 分页查询
     *
     * @param dto 筛选条件
     * @return 查询结果
     */
    @ApiOperation(value = "分页查询")
    @PostMapping("/queryPage")
    public R queryByPage(@RequestBody TestPaperDto dto, HttpServletRequest request) {
        return R.ok(testPaperService.queryByPage(dto));
    }
    /**
     * 分页查询
     *
     * @param dto 筛选条件
     * @return 查询结果
     */
    @ApiOperation(value = "分页查询所有发卷记录")
    @PostMapping("/querySendLogPage")
    @ApiResponses({
            @ApiResponse(code = 200, message = "OK", response = TestPaperLog.class),
    })
    public R querySendLogPage(@RequestBody TestPaperDto dto, HttpServletRequest request) {
        return R.ok(testPaperService.queryPageSendLog(dto));
    }


    /**
     * 分页查询
     *
     * @param dto 筛选条件
     * @return 查询结果
     */
    @ApiOperation(value = "条件查询")
    @PostMapping("/queryAll")
    public R queryAll(@RequestBody TestPaperDto dto, HttpServletRequest request) {
        return R.ok(testPaperService.queryAll(dto));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation(value = "主键查询")
    @GetMapping("/queryById")
    public R<TestPaper> queryById(@RequestParam("id") Integer id) {
        return R.ok(testPaperService.queryById(id));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation(value = "根据试卷id查询试卷详情")
    @GetMapping("/queryPaperDetail")
    public R<?> queryPaperDetail(@RequestParam("id") Integer id) {
        return R.ok(testPaperService.queryPaperDetail(id));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param aiPaperInsertDto 主键
     * @return 单条数据
     */
    @ApiOperation(value = "生成Ai试卷")
    @PostMapping("/generateAiPaper")
    public R<?> generateAiPaper(@RequestBody AiPaperInsertDto aiPaperInsertDto) {
        log.info("生成Ai试卷接口入参:" + JSONObject.toJSONString(aiPaperInsertDto));
        /** 生成ai试卷实际处理（逻辑） unfeat */
        List<TestPaper> testPapers = testPaperService.handleLogicAutoPaper(aiPaperInsertDto);
        return R.ok(200, testPapers.size() + "套智能卷子生成成功", testPapers.size() + "套智能卷子生成成功");
    }

    /**
     * 生成错题答卷
     *
     * @param faultPaperInsertDto 生成错题答卷入参
     * @return 单条数据
     */
    @ApiOperation(value = "生成错题答卷")
    @PostMapping("/generateFaultPaper")
    public R<?> generateFaultPaper(@RequestBody FaultPaperInsertDto faultPaperInsertDto) {
        if(StringUtils.isEmpty(faultPaperInsertDto.getLevel())){
            return R.failure("生成错题试卷学层不能为空");
        }
        if(StringUtils.isEmpty(faultPaperInsertDto.getGrade())){
            return R.failure("生成错题试卷年级不能为空");
        }
        if(StringUtils.isEmpty(faultPaperInsertDto.getSubject())){
            return R.failure("生成错题试卷科目不能为空");
        }
        if(null==faultPaperInsertDto.getUserid()){
            return R.failure("生成错题试卷用户id不能为空");
        }
        TestPaperDto dto = new TestPaperDto();
        dto.setPaperType(3);
        testPaperService.queryAll(dto);
        log.info("生成错题答卷接口入参:" + JSONObject.toJSONString(faultPaperInsertDto));
        Suser suser = new Suser();
        if (StringUtils.isEmpty(faultPaperInsertDto.getUsername()) && null == faultPaperInsertDto.getUserid()) {
            return R.failure("用户id或者用户名必传");
        }
        if (StringUtils.isEmpty(faultPaperInsertDto.getUsername())) {
            suser = suserService.queryById(faultPaperInsertDto.getUserid());
            faultPaperInsertDto.setUsername(suser.getUsername());
        }
        /** 生成ai试卷实际处理（逻辑） */
        TestPaper testPaper = testPaperService.handleFaultPaper(faultPaperInsertDto);
        if(null==testPaper){
            return R.failure("您还没有错题记录");
        }
        return R.ok(testPaper.getPaperName() + "+卷子生成成功");
    }

    public List<StuLabelQuestionRes> calStuTagQuestionAndCont(List<StudentQuestionTagWeights> studentQuestionTagWeights) {
        return new ArrayList<StuLabelQuestionRes>();
    }

    /**
     * 新增数据
     *
     * @param testPaper 实体
     * @return 新增结果
     */
    @ApiOperation(value = "新增数据")
    @PostMapping("/save")
    public R<TestPaper> add(@RequestBody TestPaper testPaper) {
        testPaper.setLeftPosCnt(testPaper.getQuestionCount());
        if (null == testPaper.getPaperType()) {
            return R.failure("试卷类型不能为空");
        }
        if (1 == testPaper.getPaperType() && (null == testPaper.getRightScore() || null == testPaper.getWrongScore() || null == testPaper.getEmptyScore())) {
            return R.failure("手动试卷，每道题答对分数，答错分数，不答分数不能为空");
        }
        return R.ok(testPaperService.insert(testPaper));
    }

    /**
     * 编辑数据
     *
     * @param testPaper 实体
     * @return 编辑结果
     */
    @ApiOperation(value = "编辑数据")
    @PostMapping("/update")
    public R<TestPaper> edit(@RequestBody TestPaper testPaper) {
        if (null != testPaper.getStatus() && 1 == testPaper.getStatus()) {
            List<PaperUser> list = new ArrayList<>();
            /** 发卷流程要发到卷子用户关系表 */
            if (CollectionUtils.isNotEmpty(testPaper.getUserIds())) {
                for (Integer suId : testPaper.getUserIds()) {
                    PaperUser paperUser = new PaperUser();
                    paperUser.setPaperId(testPaper.getId() + "");
                    paperUser.setUserId(suId + "");
                    /** 发卷试卷开考时间重要存在PaperUser */
                    if (null != testPaper.getStartDoTime()) {
                        paperUser.setStartDoTime(testPaper.getStartDoTime());
                    }
                    /** 发卷试卷持续时长很重要存在PaperUser */
                    if(null!=testPaper.getDueTime()){
                        paperUser.setDueTime(testPaper.getDueTime());
                    }
                    paperUser.setCrtDt(new Date());
                    paperUser.setOptDt(new Date());
                    if (null != testPaper.getCrtId()) {
                        paperUser.setCrtId(testPaper.getCrtId());
                    }
                    paperUser.setStatus(1);
                    list.add(paperUser);
                }
                paperUserService.insertBatch(list);
            } else {
                return R.failure("发卷用户id集合不能为空");
            }

        }
        return R.ok(testPaperService.update(testPaper));
    }

    /**
     * 批量编辑数据
     *
     * @param list
     * @return 编辑结果
     */
    @ApiOperation(value = "批量编辑数据")
    @PostMapping("/updateBatch")
    public R<?> editBatch(@RequestBody List<TestPaper> list) {
        return R.ok(testPaperService.updateBatch(list));
    }

    /**
     * 批量编辑数据
     *
     * @param list
     * @return 编辑结果
     */
    @ApiOperation(value = "批量新增数据")
    @PostMapping("/insertBatch")
    public R insertBatch(@RequestBody List<TestPaper> list) {
        list.forEach(testPaper -> {
            testPaper.setLeftPosCnt(testPaper.getQuestionCount());
        });
        return R.ok(testPaperService.insertBatch(list));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @GetMapping("/deleteById")
    @ApiOperation(value = "删除数据")
    public R<Boolean> deleteById(@RequestParam("id") Integer id) {
        testPaperService.deleteById(id);
        return R.ok(paperQuestionService.deleteByPaperId(id));
    }

    /**
     * 删除试卷集合
     *
     * @param dto 入参
     * @return 删除是否成功
     */
    @PostMapping("/deleteByIds")
    @ApiOperation(value = "删除试卷集合")
    public R<Boolean> deleteByIds(@RequestBody TestPaperDelDto dto) {
        testPaperService.deleteByIds(dto.getIds());
        paperQuestionService.deleteByPaperIds(dto.getIds());
        return R.ok(paperQuestionService.deleteByPaperIds(dto.getIds()));
    }

}

